package com.hmy.contract.service.contract.create.lease;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmy.ccp.common.result.FeignResult;
import com.hmy.ccp.starter.web.exception.ServiceException;
import com.hmy.contract.bo.request.oss.OssFileUploadRequest;
import com.hmy.contract.bo.response.oss.OssFileUploadResponse;
import com.hmy.contract.common.utils.OssFilePathUtil;
import com.hmy.contract.commons.enums.ContractStatusEnum;
import com.hmy.contract.dal.mapper.ContractMapper;
import com.hmy.contract.dal.po.ContractPo;
import com.hmy.contract.manager.signature.SignatureFeignClientManager;
import com.hmy.contract.service.contract.create.IContractCreateService;
import com.hmy.contract.service.dto.contract.ContractRevokeDto;
import com.hmy.contract.service.dto.contract.FieldDto;
import com.hmy.contract.service.oss.IOssService;
import com.hmy.contract.service.rdto.ContractConfigRdto;
import com.hmy.contract.service.rdto.ContractRdto;
import com.hmy.contract.service.rdto.CreateContractRdto;
import com.hmy.infrastructure.api.bo.request.signature.FieldApi;
import com.hmy.infrastructure.api.bo.request.signature.FileTemplateFieldFillApiRequest;
import com.hmy.infrastructure.api.bo.response.signature.FileTemplateFieldFillApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author seven.qi 齐胜南
 * @version 1.0
 * @description
 * @date 2023/12/23 16:12
 */
@Service
@Slf4j
public class PaperLeaseContractCreateService implements IContractCreateService {

    @Resource
    private SignatureFeignClientManager signatureFeignClientManager;

    @Resource
    private IOssService ossService;

    @Resource
    private ContractMapper contractMapper;

    @Override
    public String create(CreateContractRdto createContractDto) {
        // 返回文件模板id
        return createContractDto.getContractConfigRdto().getSignTemplateId();
    }

    @Override
    public List<FieldDto> fillFieldValue(CreateContractRdto createContractDto) {
        List<FieldDto> fieldList = new ArrayList<>();
        Map<String, Object> fieldMap = createContractDto.getFieldMap();
        for (String key : fieldMap.keySet()) {
            fieldList.add(FieldDto.builder().key(key).value(fieldMap.get(key).toString()).build());
        }
        return fieldList;
    }

    @Override
    public String start(String signTaskId, List<FieldDto> fieldDtoList, CreateContractRdto dto) {
        ContractConfigRdto configRdto = dto.getContractConfigRdto();
        List<FieldApi> fieldApiList = BeanUtil.copyToList(fieldDtoList, FieldApi.class);

        FileTemplateFieldFillApiRequest fileTemplateFieldFillApiRequest = new FileTemplateFieldFillApiRequest();
        fileTemplateFieldFillApiRequest.setFileTemplateId(signTaskId);
        fileTemplateFieldFillApiRequest.setFieldList(fieldApiList);
        fileTemplateFieldFillApiRequest.setFileName(configRdto.getTaskSubject());
        FeignResult<FileTemplateFieldFillApiResponse> response = null;
        try {
            response = signatureFeignClientManager.fileTemplateFieldFill(fileTemplateFieldFillApiRequest);
        } catch (Exception e) {
            log.error("fileTemplateFieldFill exception", e);
            throw new ServiceException("502000003", "");
        }

        String fileUrl = response.getData().getFileUrl();
        String storePath = OssFilePathUtil.createPaperContractPath(dto.getContractNo());
        if (StrUtil.isNotEmpty(fileUrl)) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            HttpUtil.download(fileUrl, outputStream, true);
            OssFileUploadRequest ossFileUploadRequest = new OssFileUploadRequest();
            ossFileUploadRequest.setInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
            ossFileUploadRequest.setStorePath(storePath);
            OssFileUploadResponse ossFileUploadResponse = ossService.ossFileUploadByStream(ossFileUploadRequest);
            storePath = ossFileUploadResponse.getOssPrefix();

        }
        return storePath;
    }

    @Override
    public void beforeCreate(CreateContractRdto dto) {

    }

    @Override
    public void afterCreate(CreateContractRdto dto) {
        ContractRdto contractRdto = dto.getContractRdto();
        ContractPo contractPo = new ContractPo();
        contractPo.setStatus(ContractStatusEnum.WAITING_UPLOAD.getStatus());
        contractPo.setContractTaskId(contractRdto.getContractTaskId());
        contractPo.setContractFileUrl(dto.getUrl());
        LambdaQueryWrapper<ContractPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ContractPo::getContractId, contractRdto.getContractId());
        wrapper.eq(ContractPo::getIsDeleted, Boolean.FALSE);
        contractMapper.update(contractPo, wrapper);
    }

    @Override
    public Long notify(ContractRevokeDto dto) {
        return null;
    }
}
